<template>
  <div class="login">
    <div class="login-bg">
      <div class="bg">
        <!-- Background image or gradient will be added via CSS -->
      </div>
    </div>

    <canvas id='canvas'></canvas>
    <div class="login-container" :class="{'error-shake': loginError}">
      <div class="logo-container">
        <div class="logo">礼品管理</div>
      </div>
      <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
        <div class="form-header">
          <h3 class="title">欢迎登录</h3>
          <p class="subtitle">请输入您的账号和密码</p>
        </div>

        <el-form-item prop="username">
          <el-input v-model="loginForm.username" type="text" size="large" auto-complete="off" placeholder="账号">
            <template #prefix>
              <svg-icon icon-class="user" class="el-input__icon input-icon" />
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input v-model="loginForm.password" :type="passwordVisible ? 'text' : 'password'" size="large" auto-complete="off" placeholder="密码"
            @keyup.enter="handleLogin">
            <template #prefix>
              <svg-icon icon-class="password" class="el-input__icon input-icon" />
            </template>
            <template #suffix>
              <svg-icon :icon-class="passwordVisible ? 'eye-open' : 'eye'" class="el-input__icon input-icon show-pwd" @click="passwordVisible = !passwordVisible" />
            </template>
          </el-input>
        </el-form-item>

        <div class="login-options">
          <el-checkbox v-model="loginForm.rememberMe" class="remember-me">记住密码</el-checkbox>
          <a href="javascript:void(0)" class="forgot-password">忘记密码?</a>
        </div>

        <el-form-item style="width:100%;">
          <el-button :loading="loading" size="large" type="primary" class="login-btn" @click.prevent="handleLogin">
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
          <div class="register-link" v-if="register">
            <router-link class="link-type" :to="'/register'">立即注册</router-link>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <div class="el-login-footer">
      <span>Copyright 2018-2024 魔术先生 All Rights Reserved.</span>
    </div>
  </div>
</template>

<script setup>
import { getCodeImg } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import { useUserStore } from '@/store/modules/user'
import { ref, watch, getCurrentInstance, onMounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const userStore = useUserStore()
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();

const loginForm = ref({
  username: "",
  password: "",
  rememberMe: false,
});

const passwordVisible = ref(false);

const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
};

const loading = ref(false);
const register = ref(false);
const redirect = ref(undefined);
const loginError = ref(false);

watch(route, (newRoute) => {
  redirect.value = newRoute.query && newRoute.query.redirect;
}, { immediate: true });

function handleLogin() {
  proxy.$refs.loginRef.validate(valid => {
    if (valid) {
      console.log('Complete form data:', {
        username: loginForm.value.username,
        password: loginForm.value.password,
      });
      loading.value = true;
      //console.log('-----encrypt password-----',encrypt(loginForm.value.password))
      if (loginForm.value.rememberMe) {
        Cookies.set("username", loginForm.value.username, { expires: 30 });
        Cookies.set("password", loginForm.value.password, { expires: 30 });
        Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
      } else {
        Cookies.remove("username");
        Cookies.remove("password");
        Cookies.remove("rememberMe");
      }
      // 
      const loginParams = {
        username: loginForm.value.username,
        password: loginForm.value.password
      };
      console.log('-----loginParams-----', loginParams);
      userStore.login(loginParams).then(() => {
        const query = route.query;
        const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
          if (cur !== "redirect") {
            acc[cur] = query[cur];
          }
          return acc;
        }, {});
        router.push({ path: redirect.value || "/", query: otherQueryParams });
      }).catch(() => {
        loading.value = false;
        loginError.value = true;
        setTimeout(() => {
          loginError.value = false;
        }, 500);
      });
    }
  });
}

function getCookie() {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  loginForm.value = {
    ...loginForm.value, // 
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : password,
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
  };
}

let animationFrameId = null;

onMounted(() => {
  // initCanvas();
  createParticles();
});

onBeforeUnmount(() => {
  if (animationFrameId) {
    cancelAnimationFrame(animationFrameId);
  }
});

function createParticles() {
  const container = document.querySelector('.cyber-particles');
  if (!container) return;

  for (let i = 0; i < 50; i++) {
    const particle = document.createElement('div');
    particle.className = 'particle';
    particle.style.left = Math.random() * 100 + '%';
    particle.style.top = Math.random() * 100 + '%';
    particle.style.animationDelay = Math.random() * 5 + 's';
    particle.style.animationDuration = (Math.random() * 5 + 5) + 's';
    container.appendChild(particle);
  }
}
getCookie();
</script>

<style lang='scss' scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
  overflow: hidden;
  position: relative;
  background: linear-gradient(135deg, #6e8efb, #a777e3);
}

.login-bg {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  z-index: 1;
  
  .bg {
    width: 100%;
    height: 100%;
    background-size: cover;
    background-position: center;
    filter: blur(5px);
    opacity: 0.8;
  }
}

canvas {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  opacity: 0.3;
  pointer-events: none;
  z-index: 2;
}

.login-container {
  position: relative;
  z-index: 10;
  width: 420px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1),
              0 5px 15px rgba(0, 0, 0, 0.07);
  transition: all 0.3s ease;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    background: linear-gradient(
      to bottom right,
      rgba(255, 255, 255, 0.1),
      rgba(255, 255, 255, 0.05)
    );
    transform: rotate(30deg);
    pointer-events: none;
    z-index: -1;
  }

  &.error-shake {
    animation: shake 0.5s cubic-bezier(.36,.07,.19,.97) both;
    transform: translate3d(0, 0, 0);
    backface-visibility: hidden;
    perspective: 1000px;
    border: 1px solid #ff4d4f;
    box-shadow: 0 15px 35px rgba(255, 77, 79, 0.1),
                0 5px 15px rgba(255, 77, 79, 0.07);
  }
}

.logo-container {
  text-align: center;
  margin-bottom: 20px;
  
  .logo {
    font-size: 28px;
    font-weight: 700;
    color: #409eff;
    background: linear-gradient(45deg, #409eff, #36d1dc);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    letter-spacing: 1px;
  }
}

@keyframes shake {
  10%, 90% {
    transform: translate3d(-1px, 0, 0);
  }
  
  20%, 80% {
    transform: translate3d(2px, 0, 0);
  }

  30%, 50%, 70% {
    transform: translate3d(-4px, 0, 0);
  }

  40%, 60% {
    transform: translate3d(4px, 0, 0);
  }
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
  
  .title {
    font-size: 24px;
    color: #333333;
    margin: 0 0 8px;
    font-weight: 600;
    text-shadow: none;
  }
  
  .subtitle {
    font-size: 14px;
    color: #909399;
    margin: 0;
  }
}

.el-input {
  background: transparent!important;
  
  :deep(.el-input__wrapper) {
    background: #f5f7fa!important;
    border: none;
    box-shadow: none !important;
    border-radius: 12px;
    padding: 0 15px;
    height: 50px;
    transition: all 0.3s ease;
    
    &.is-focus {
      background: #fff!important;
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2) !important;
    }
    
    &:hover {
      background: #fff!important;
    }
  }
  
  :deep(.el-input__inner) {
    color: #606266;
    line-height: 50px;
    font-size: 15px;
    
    &::placeholder {
      color: #c0c4cc;
    }

    &:-webkit-autofill,
    &:-webkit-autofill:hover,
    &:-webkit-autofill:focus,
    &:-webkit-autofill:active {
      -webkit-text-fill-color: #606266 !important;
      -webkit-box-shadow: 0 0 0 30px #f5f7fa inset !important;
      transition: background-color 5000s ease-in-out 0s;
    }
  }
}

.input-icon {
  color: #909399;
  font-size: 18px;
  cursor: pointer;
  
  &.show-pwd {
    &:hover {
      color: #409eff;
    }
  }
}

.login-form {
  .el-form-item {
    margin-bottom: 25px;
  }
}

.login-btn {
  width: 100%;
  height: 50px;
  background: linear-gradient(45deg, #409eff, #36d1dc);
  border: none;
  font-size: 16px;
  font-weight: 600;
  border-radius: 12px;
  margin-top: 10px;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(64, 158, 255, 0.3);
  }
  
  &:active {
    transform: translateY(0);
    box-shadow: 0 4px 10px rgba(64, 158, 255, 0.2);
  }
}

.remember-me {
  color: #606266;
  
  :deep(.el-checkbox__label) {
    color: #606266;
    font-size: 14px;
  }
  
  :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
    background-color: #409eff;
    border-color: #409eff;
  }
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.forgot-password {
  color: #909399;
  font-size: 14px;
  text-decoration: none;
  transition: color 0.3s ease;
  
  &:hover {
    color: #409eff;
    text-decoration: none;
  }
}

.register-link {
  text-align: center;
  margin-top: 20px;
  
  .link-type {
    color: #409eff;
    text-decoration: none;
    font-size: 14px;
    transition: all 0.3s ease;
    
    &:hover {
      color: #66b1ff;
      text-decoration: underline;
    }
  }
}

.el-login-footer {
  position: absolute;
  bottom: 20px;
  width: 100%;
  text-align: center;
  color: rgba(255, 255, 255, 0.8);
  z-index: 10;
  font-size: 12px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

// Particle animation
.cyber-particles {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  pointer-events: none;
}

.particle {
  position: absolute;
  background-color: rgba(255, 255, 255, 0.8);
  width: 3px;
  height: 3px;
  border-radius: 50%;
  animation: float 15s infinite ease-in-out;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0) translateX(0);
  }
  25% {
    transform: translateY(-30px) translateX(30px);
  }
  50% {
    transform: translateY(-15px) translateX(-15px);
  }
  75% {
    transform: translateY(30px) translateX(15px);
  }
}
</style>